package userservice

import (
	"model/usermodel"
	"services"
	"verification"
)

// 登录
func Login(userName string, password string) services.Response {
	user, error := usermodel.GetUser(userName)
	if error != nil {
		return services.Response{
			Code:    100,
			Success: false,
			Message: "查无此人",
			Data:    error,
		}
	}
	if user.Password != password {
		return services.Response{
			Code:    101,
			Success: false,
			Message: "密码错误",
			Data:    nil,
		}
	}
	token, error := verification.Sign(verification.Context{ID: user.Id, Username: user.Name})
	if error != nil {
		return services.Response{
			Code:    102,
			Success: false,
			Message: "生成token错误",
			Data:    error,
		}
	}
	message, err := usermodel.SetTokenToRedis(token, usermodel.UserInfo{Id: user.Id, Name: user.Name, Password: user.Password, Phone: user.Phone, Email: user.Email})
	if err != nil {
		return services.Response{
			Code:    102,
			Success: false,
			Message: message,
			Data:    error,
		}
	}
	return services.Response{
		Code:    200,
		Success: true,
		Message: "",
		Data: LoginResult{
			Authorization: token,
			Name:          user.Name,
			Phone:         user.Phone,
			Email:         user.Email,
		},
	}
}

type LoginResult struct {
	Authorization string
	Name          string
	Phone         string
	Email         string
}
